<template>
  <div>
    <el-card class="login-form-layout">
      <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
        <div style="text-align: center">
          <svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon>
        </div>
        <h2 class="login-title color-main">mall-admin-web</h2>
        <el-form-item prop="username">
          <el-input name="username" type="text" v-model="loginForm.userId" autoComplete="on" placeholder="请输入员工工号">
            <span slot="prefix">
              <svg-icon icon-class="user" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.userPassword"
            autoComplete="on" placeholder="请输入密码">
            <span slot="prefix">
              <svg-icon icon-class="password" class="color-main"></svg-icon>
            </span>
            <span slot="suffix" @click="showPwd">
              <svg-icon icon-class="eye" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px;text-align: center">

          <el-button style="width: 45%" type="primary" :loading="loading" @click.native.prevent="clickLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <img :src="login_center_bg" class="login-center-layout">

  </div>
</template>

<script>
import { isvalidUsername } from '@/utils/validate';
import { setCookie, getCookie } from '@/utils/support';
import login_center_bg from '@/assets/images/login_center_bg.png'
import { login } from '../../api/page';

export default {
  name: 'login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error('密码不能小于3位'))
      } else {
        callback()
      }
    };
    return {
      loginForm: {
        userId: '',
        userPassword: '',
      },
      loginRules: {
        userId: [{ required: true, trigger: 'blur', validator: validateUsername }],
        userPassword: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      loading: false,
      pwdType: 'password',
      login_center_bg,
      dialogVisible: false,
      supportDialogVisible: false
    }
  },
  created() {
    this.loginForm.username = getCookie("username");
    this.loginForm.password = getCookie("password");
    if (this.loginForm.username === undefined || this.loginForm.username == null || this.loginForm.username === '') {
      this.loginForm.username = 'admin';
    }
    if (this.loginForm.password === undefined || this.loginForm.password == null) {
      this.loginForm.password = 'macro123';
    }
  },

  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },


    clickLogin() {
      const data = {
        userId: this.loginForm.userId,
        userPassword: this.loginForm.userPassword
      };

      console.log(data); // 打印出要发送的数据以供调试

      this.loading = true; // 开始请求时设置加载状态为 true

      login(data)
        .then(data => {
          console.log('Success:', data);
          if (data && data.state === 200) {
            setCookie("username", this.loginForm.userId, 15);
            setCookie("password", this.loginForm.userPassword, 15);

            this.$store.dispatch('login'); // 更新登录状态
            const redirectTo = this.$route.query.redirect || '/home';
            this.$router.push(redirectTo); // 导航到之前尝试访问的页面或默认首页
          } else {
            alert('登录失败，请检查用户名和密码');
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
        .finally(() => {
          this.loading = false; // 请求完成后总是将加载状态设置为 false
        });
    }
  }
}
</script>

<style scoped>
.login-form-layout {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 140px auto;
  border-top: 10px solid #409EFF;
}

.login-title {
  text-align: center;
}

.login-center-layout {
  background: #409EFF;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
</style>
